package com.wdciti.sccp.iot.springvertx;

import com.wdciti.sccp.iot.common.endpoint.Endpoint;
import com.wdciti.sccp.iot.springvertx.protocols.tcp.ext.B2mDecoderFactory;
import com.wdciti.sccp.iot.springvertx.protocols.tcp.ext.EndpointHeadersAdaptor;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.DeliveryOptions;
import lombok.Getter;

/**
 * @author by early
 */
public class EndPointVerticle extends AbstractVerticle implements Endpoint {
//TODO: 还需要抽象接口

    public static final String SPA = "@";
    public static final String PROTOCOL = "ely://";
    // from remote to this means in.
    public static final String IN = "/in";

    // from this to remote means out.
    public static final String OUT = "/out";
    public static final String DUMP = "/dump";
    public static final String READY = "/ready";
    private static final String READY_ADDR = PROTOCOL + "endpointVerticle/ready";
    private static final String DUMP_BUS_ADDR = PROTOCOL + "NetHandler/HexDump";

    @Getter
    public String busAddr;
    //    @Getter
//    protected String template;
    @Getter
    protected String id;
    @Getter
    protected ByteToMessageDecoder decoder;
    @Getter
    protected String codecName;

    public static String getReadyAddr() {
        return READY_ADDR;
    }

    public static String getDumpAddr() {
        return DUMP_BUS_ADDR;
    }

    @Override
    public void init(Vertx vertx, Context context) {
        super.init(vertx, context);
        this.id = config().getString("id");
        this.busAddr = PROTOCOL + id;
        if(decoder == null){
            this.decoder = B2mDecoderFactory.get(config().getString("decoder"));
            this.codecName = config().getString("codec", null);
        }

    }

    protected void promiseReady() {
        MultiMap map = EndpointHeadersAdaptor.emptyHeaders().addBusAddr(this.busAddr, READY).headers();
        DeliveryOptions readyOpt = new DeliveryOptions().setHeaders(map);
        vertx.eventBus().publish(getReadyAddr(), Buffer.buffer().appendInt(0x0f), readyOpt);
    }

}
